//
//  CustomToastView.m
//  jyb
//
//  Created by Jiuwu on 14/12/30.
//  Copyright (c) 2014年 apple. All rights reserved.
//

#import "CustomToastView.h"
#import "AppDelegate.h"

#define kScreenHeight [UIScreen mainScreen].bounds.size.height
#define kScreenWidth  [UIScreen mainScreen].bounds.size.width
#define kToastMargin 10
#define kTotalOffset 20


@interface CustomToastView () {
    UIView *_overlay;
    BOOL _isShow;
}

@property (strong, nonatomic) UIView *overlay;

@end

@implementation CustomToastView

@synthesize parentView = _parentView;

#pragma mark - Init

- (id)initWithFrame:(CGRect)frame {
    return [self initWithFrame:frame bgColor:[[UIColor blackColor] colorWithAlphaComponent:0.7f]];
}

- (instancetype)initWithFrame:(CGRect)frame bgColor:(UIColor *)backgroundColor {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = backgroundColor;
        self.bgColor = backgroundColor;
        self.layer.cornerRadius = 6.0f;
        self.layer.masksToBounds = YES;
        _textLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _textLabel.numberOfLines = 0;
        _textLabel.font = [UIFont systemFontOfSize:15];
        _textLabel.textAlignment = NSTextAlignmentCenter;
        _textLabel.textColor = [UIColor whiteColor];
        _textLabel.backgroundColor = [UIColor clearColor];
        [self addSubview:_textLabel];
        _queueCount = 0;
    }
    return self;
}

#pragma mark - Change style

- (void)setBgColor:(UIColor *)bgColor {
    self.backgroundColor = bgColor;
}

- (void)setText:(NSString *)text {
    _textLabel.frame = CGRectMake(0, 10, 300, 10);
    _queueCount ++;
    self.alpha = 1.0f;
    _textLabel.text = text;
    [_textLabel sizeToFit];
    _textLabel.frame = CGRectMake(kToastMargin, kToastMargin, _textLabel.frame.size.width, _textLabel.frame.size.height);
    self.frame =  CGRectMake((_parentView.frame.size.width - _textLabel.frame.size.width - kTotalOffset)/2, self.frame.origin.y, _textLabel.frame.size.width + kTotalOffset, _textLabel.frame.size.height + kTotalOffset);
    self.layer.cornerRadius = CGRectGetHeight(self.frame)/2;
    self.layer.masksToBounds = YES;
    [UIView animateWithDuration:3.0 delay:0.0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
        self.alpha = 0;
    } completion:^(BOOL finished){
        if (_queueCount == 1) {
            [self removeFromSuperview];
        }
        _queueCount--;
    }];
}

- (void)showToastMessage:(NSString *)text {
    
    _textLabel.frame = CGRectMake(0, 10, 300, 10);
    _queueCount ++;
    self.alpha = 1.0f;
    _textLabel.text = text;
    [_textLabel sizeToFit];
}

#pragma mark - Show

- (void)showWithAnimation:(ToastAnimationStyle)animationStyle {
    [self showToastMessage:self.labelText];
    
    switch (animationStyle) {
        case ToastAnimationStyleFade:
        {
            // change alpha value 
            _textLabel.frame = CGRectMake(kToastMargin, kToastMargin, _textLabel.frame.size.width, _textLabel.frame.size.height);
            CGFloat toastWidth = _textLabel.frame.size.width + kTotalOffset;
            CGFloat toastHeight = _textLabel.frame.size.height + kTotalOffset;
            self.frame = CGRectMake((kScreenWidth - toastWidth)/2, (kScreenHeight - 100 - toastHeight), toastWidth, toastHeight);
            self.layer.cornerRadius = CGRectGetHeight(self.frame)/2;
            self.layer.masksToBounds = YES;
            [UIView animateWithDuration:0.5 delay:1.0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
                self.alpha = 0;
            } completion:^(BOOL finished){
                [self removeToastFromSuperview];
            }];
        }
            break;
        case ToastAnimationStyleTip:
        {
            // show below navigation bar as a tip
            _textLabel.font = [UIFont systemFontOfSize:14];
            [_textLabel sizeToFit];
            CGFloat toastHeight = _textLabel.frame.size.height + kTotalOffset;
            self.frame = CGRectMake(15, 64, kScreenWidth - 30, 0);
            _textLabel.frame = CGRectMake(kToastMargin, kToastMargin, self.frame.size.width - kTotalOffset, _textLabel.frame.size.height);
            [UIView animateWithDuration:0.2f delay:0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
                CGRect tempFrame = self.frame;
                tempFrame.size.height = toastHeight;
                tempFrame.origin.y += 10;
                self.frame = tempFrame;
            } completion:^(BOOL finished) {
                [self performSelector:@selector(removeTip:) withObject:[NSNumber numberWithFloat:64] afterDelay:2.f];
            }];
        }
            break;
        case ToastAnimationStylePopFromTop:
        {
            // show from top of window, cover whole navigation bar
            self.layer.cornerRadius = 0.;
            CGFloat toastHeight = 64;
            self.frame = CGRectMake(0, 0, kScreenWidth, 0);
            _textLabel.frame = CGRectMake(kToastMargin, 64 - _textLabel.frame.size.height - 10, self.frame.size.width - kTotalOffset, _textLabel.frame.size.height);
            [UIView animateWithDuration:0.25f animations:^{
                CGRect tempFrame = self.frame;
                tempFrame.size.height = toastHeight;
                self.frame = tempFrame;
            } completion:^(BOOL finished) {
                [self performSelector:@selector(removeTip:) withObject:[NSNumber numberWithFloat:0] afterDelay:2.f];
            }];
        }
            break;
        case ToastAnimationStylePopFromMiddle:
        {
            // show from middle of the window
            _textLabel.frame = CGRectMake(kToastMargin, kToastMargin, _textLabel.frame.size.width, _textLabel.frame.size.height);
            CGFloat toastWidth = _textLabel.frame.size.width + kTotalOffset;
            CGFloat toastHeight = _textLabel.frame.size.height + kTotalOffset;
            self.frame = CGRectMake(kScreenWidth/2, kScreenHeight/2, 0, 0);
            [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
                self.frame = CGRectMake((kScreenWidth - toastWidth)/2, (kScreenHeight - toastHeight)/2, toastWidth, toastHeight);
            } completion:^(BOOL finished) {
                [self performSelector:@selector(removeWithScale) withObject:nil afterDelay:2.f];
            }];
        }
            break;
        case ToastAnimationStylePopFromBottom:
        {
            // show from bottom of the window
            _textLabel.frame = CGRectMake(kToastMargin, kToastMargin, _textLabel.frame.size.width, _textLabel.frame.size.height);
            CGFloat toastWidth = _textLabel.frame.size.width + kTotalOffset;
            CGFloat toastHeight = _textLabel.frame.size.height + kTotalOffset;
            self.frame = CGRectMake((kScreenWidth - toastWidth)/2, kScreenHeight, toastWidth, toastHeight);
            [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
                CGRect frame = self.frame;
                frame.origin.y = kScreenHeight - 100 - toastHeight;
                self.frame = frame;
            } completion:^(BOOL finished) {
                CAKeyframeAnimation *shakeAnim = [CAKeyframeAnimation animation];
                shakeAnim.keyPath = @"transform.translation.y";
                shakeAnim.duration = 0.25;
                shakeAnim.values = @[ @(0), @(-20), @(0)];
                [self.layer addAnimation:shakeAnim forKey:nil];
                [self performSelector:@selector(removeFromSuperview) withObject:nil afterDelay:2.f];
            }];
        }
            break;
        default:
            break;
    }
}

#pragma mark - Dismiss

- (void)removeTip:(NSNumber *)originY {
    [UIView animateWithDuration:0.25f delay:0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
        CGRect tempFrame = self.frame;
        tempFrame.origin.y = originY.floatValue;
        tempFrame.size.height = 0;
        self.frame = tempFrame;
    } completion:^(BOOL finished) {
        [self removeToastFromSuperview];
    }];
}

- (void)removeWithScale {
    [UIView animateWithDuration:0.25f delay:0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
        self.frame = CGRectMake(kScreenWidth/2, kScreenHeight/2, 0, 0);
    } completion:^(BOOL finished) {
        [self removeToastFromSuperview];
    }];
}

- (void)removeToastFromSuperview {
    self.layer.cornerRadius = 6.0f;
    if (_queueCount == 1) {
        [self removeFromSuperview];
    }
    _queueCount--;
}

#pragma mark - Static methods

+ (void)toast:(NSString *)title {
    [self toast:title style:ToastAnimationStyleFade];
}

+ (void)toast:(NSString *)title style:(ToastAnimationStyle)animationStyle {
    [self toast:title style:animationStyle color:[[UIColor blackColor] colorWithAlphaComponent:0.8]];
}

+ (void)toast:(NSString *)title style:(ToastAnimationStyle)animationStyle color:(UIColor *)bgColor {
    [self hideAllToastsForView:[UIApplication sharedApplication].keyWindow];
    CustomToastView *toast = [[self alloc] initWithFrame:CGRectZero bgColor:bgColor];
    [[UIApplication sharedApplication].keyWindow addSubview:toast];
    toast.labelText = title;
    [toast showWithAnimation:animationStyle];
}

+ (NSArray *)toastForView:(UIView *)view {
    NSMutableArray *toasts = [NSMutableArray array];
    NSArray *subviews = view.subviews;
    for (UIView *aView in subviews) {
        if ([aView isKindOfClass:self]) {
            [toasts addObject:aView];
        }
    }
    return [NSArray arrayWithArray:toasts];
}

+ (NSUInteger)hideAllToastsForView:(UIView *)view {
    NSArray *toasts = [CustomToastView toastForView:view];
    for (CustomToastView *toast in toasts) {
        [toast performSelector:@selector(removeToastFromSuperview)];
    }
    return [toasts count];
}

- (UIView *)overlay {
    if (!_overlay) {
        _overlay = [[UIView alloc] initWithFrame:[UIApplication sharedApplication].keyWindow.bounds];
        _overlay.backgroundColor = [UIColor clearColor];
    }
    return _overlay;
}

@end
